package com.shuqing.download.engine.config;

import com.shuqing.download.engine.constants.BaseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author wangshuqing
 * @date 2023/2/12 15:35
 */
@Configuration
public class ThreadConfig {

    @Autowired
    private EngineConfig engineConfig;

    @Bean(BaseConstants.THREAD_POOL_NAME)
    public ThreadPoolTaskExecutor  getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(engineConfig.getCorePoolSize());
        //最大线程数
        executor.setMaxPoolSize(engineConfig.getCorePoolSize());
        //队列容量
        executor.setQueueCapacity(engineConfig.getMaxTaskCount());
        //活跃时间
        executor.setKeepAliveSeconds(engineConfig.getThreadKeepAliveSeconds());
        //线程名字前缀
        executor.setThreadNamePrefix("down-main-");
        executor.setBeanName(BaseConstants.THREAD_POOL_NAME);
        /*
            当poolSize已达到maxPoolSize，如何处理新任务（是拒绝还是交由其它线程处理）
            CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
